package com.feijiang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feijiang.entity.ExpeRecord;
import com.feijiang.mapper.ExpeRecordMapper;
import com.feijiang.service.IExpeRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feijiang.util.MyPage;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-12-28
 */
@Service
@Slf4j
public class ExpeRecordServiceImpl extends ServiceImpl<ExpeRecordMapper, ExpeRecord> implements IExpeRecordService {

  @Resource
  ExpeRecordMapper expeRecordMapper;

  @Override
  public boolean add(ExpeRecord expeRecord) {
    int insert = expeRecordMapper.insert(expeRecord);
    return insert > 0;
  }

  @Override
  public boolean deleteById(int id) {
    /**
     * 如果不存在ID，则直接返回false
     */
    if (!exist(id)) {
      return false;
    }
    int i = expeRecordMapper.deleteById(id);
    log.info("删除实验记录{}条", i);
    return i > 0;
  }

  @Override
  public boolean edit(ExpeRecord expeRecord) {
    Assert.isTrue(exist(expeRecord.getId()), "id不存在");
    int i = expeRecordMapper.updateById(expeRecord);
    return i > 0;
  }

  @Override
  public MyPage queryByPage(int pageSize, int pageNum, int expeId) {
    List<ExpeRecord> expeRecords = expeRecordMapper
        .queryByPage(pageSize, (pageNum - 1) * pageSize, expeId);
    QueryWrapper<ExpeRecord> expeRecordQueryWrapper = new QueryWrapper<>();
    expeRecordQueryWrapper.eq("expe_id", expeId);
    long total = this.expeRecordMapper.selectCount(expeRecordQueryWrapper);
    return MyPage.buildPage(pageSize, pageNum, total, expeRecords);
  }

  @Override
  public MyPage listAllByPage(int pageSize, int pageNum) {
    List<ExpeRecord> expeRecords =expeRecordMapper
        .listAllByPage(pageSize, (pageNum - 1) * pageSize);
    return MyPage.buildPage(pageSize, pageNum, this.count(), expeRecords);
  }

  @Override
  public int deleteByExprId(int exprId) {
    return expeRecordMapper.deleteByExprId(exprId);
  }

  private boolean exist(int id) {
    ExpeRecord expeRecord = expeRecordMapper.selectById(id);
    return expeRecord != null;
  }
}
